package org.vectrics.recruiter.reporting;

import com.lowagie.text.Document;
import com.lowagie.text.Element;
import com.lowagie.text.PageSize;
import com.lowagie.text.Paragraph;
import com.lowagie.text.Phrase;
import com.lowagie.text.Rectangle;
import com.lowagie.text.pdf.PdfPTable;
import com.lowagie.text.pdf.PdfPCell;
import org.apache.log4j.Logger;
import org.vectrics.VectricsException;

import java.text.SimpleDateFormat;
import java.util.Locale;

import org.vectrics.domain.Domain;
import org.vectrics.provider.CoreServiceLocator;
import org.vectrics.recruiter.RecruitServiceLocator;
import org.vectrics.skill.Skill;
import org.vectrics.skill.SkillProvider;
import org.vectrics.skill.SkillRatingSet;
import org.vectrics.skill.UserEvaluation;
import org.vectrics.user.Person;



public class UserSkillRatingsReport extends RecruitBaseReport {
	private transient static Logger log = Logger.getLogger(UserSkillRatingsReport.class);

	private SimpleDateFormat dateFormatter = new SimpleDateFormat("MM-dd-yyyy");
	private PdfPTable mainTable = null;
	private String userId = null;
	private String evaluationId = null;
	//private SkillSetUtil skillSetUtil = null;
	private boolean showAllBranches = false;
	public static String NOT_GIVEN = "Not Specified";
	
	
	
	public UserSkillRatingsReport(Domain domain, Locale locale) {
		super(domain, locale);
	}

	protected Rectangle getPageSize() {
		return(PageSize.A4);
	}

	private void addCoreRow(PdfPTable coreTable, String caption, String value) {
		PdfPCell captionCell = new PdfPCell(new Phrase(caption, ReportConstants.stdBoldFont));
		captionCell.setBorderWidth(1);
		coreTable.addCell(captionCell);
		String valueStr = value;
		if ((valueStr == null) || (valueStr.length() <= 0)) {
			valueStr = NOT_GIVEN;
		}
		PdfPCell valueCell = new PdfPCell(new Phrase(valueStr, ReportConstants.stdFont));
		valueCell.setBorderWidth(1);
		valueCell.setPaddingBottom(5);
		coreTable.addCell(valueCell);
	}
	
	 
	protected void fill(Document document) throws VectricsException {
		log.debug("Skill Setup Report - building");
		try {
			UserEvaluation evaluation = RecruitServiceLocator.getSkillProvider().findEvaluationById(new Long(getEvaluationId()));
			if (evaluation == null) {
				log.error("User Evaluation not found for evaluationId = " + getEvaluationId());
				throw new VectricsException("User Evaluation not found for evaluationId = " + getEvaluationId());
			}
			
			if (getUserId() == null) {
				setUserId(evaluation.getPerson().getId().toString());
			}
			
			Person person = CoreServiceLocator.getPersonService().findPersonById(new Long(getUserId()));
			if (person == null) {
				log.error("Could not find user: " + getUserId());
				throw new VectricsException("Could not find user: " + getUserId());
			}
			
			document.add(new Paragraph("Evaluation", ReportConstants.titleFont));
			PdfPTable coreTable = new PdfPTable(2);
			coreTable.setHorizontalAlignment(Element.ALIGN_LEFT);
			coreTable.setWidthPercentage(60);
			int coreTableWidths[] = {200, 200};
			coreTable.setWidths(coreTableWidths);
			
			addCoreRow(coreTable, "Candidate", person.getName());
			String evaluatorName = NOT_GIVEN;
			if (evaluation.getLeadPerson() != null) {
				evaluatorName = evaluation.getLeadPerson().getName();
			}
			addCoreRow(coreTable, "Evaluator", evaluatorName);
			addCoreRow(coreTable, "Date", dateFormatter.format(evaluation.getDateStart()));
			addCoreRow(coreTable, "Description", evaluation.getDescription());
			addCoreRow(coreTable, "Notes", evaluation.getNotes());
			document.add(coreTable);
			
			
			SkillRatingSet ratingSet = null;
			ratingSet = RecruitServiceLocator.getSkillProvider().findUserSkillSet(evaluation);
			
			Skill rootSkill = RecruitServiceLocator.getSkillProvider().getRootSkill();
			//this.skillSetUtil = new SkillSetUtil(ratingSet, rootSkill.getTree());
			
			document.add(new Paragraph(" ", ReportConstants.stdFont));
			//document.add(new Paragraph("Skills", ReportConstants.titleFont));

			SkillRatingPdfTable skillTable = new SkillRatingPdfTable("phrase.skill.report.title", 
					this.getLocale());
			skillTable.initialize(rootSkill, ratingSet, 0);
			/*
			log.debug("fill() - setting table properties");
			mainTable = new PdfPTable(2);
			mainTable.setHorizontalAlignment(PdfPTable.ALIGN_LEFT);
			mainTable.setWidthPercentage(100);
			int mainTableWidths[] = {30, 20};
			mainTable.setWidths(mainTableWidths);

			log.debug("fill() - adding table header row");
			addTableHeaderCell("Description");
			addTableHeaderCell("Rating");
			mainTable.setHeaderRows(1);

			
			log.debug("fill() - adding job rows");
			displaySkillBranch(mainTable, rootSkill, ratingSet, 0);
			log.debug("fill() - adding job table to document");
			document.add(mainTable);
			*/
			document.add(skillTable);
		}
		catch(Exception e) {
			log.error("Exception creating pdf document - in fill()", e);
			throw new VectricsException("Exception creating pdf document - fill()", e);
		}
        
	}
	
/*
	protected void displaySkill(PdfPTable table, Skill parentSkill, 
				SkillRatingSet ratingSet, int level) throws VectricsException {
		try {
			log.debug("addJobRow() - displaying rating");
			String ratingDesc = "";
			SkillRating rating = ratingSet.findSkillRating(parentSkill);
			
			
			if (rating == null) {
				
			}
			else {
				ratingDesc = rating.getDescription();
			}
			
			
			PdfRectangle rect = new PdfRectangle(10, 20);
			
			Color color = new Color(255, 255, 255);
			
			log.debug("addJobRow() - displaying date...");
			PdfPTable descTable = new PdfPTable(3);
			int descWidths[] = {level * 10, 10, 200};
			descTable.setWidthPercentage(100);
			descTable.setWidths(descWidths);
			PdfPCell cell1 = new PdfPCell(ReportUtil.createPhrase(" ", ReportConstants.smlFont));
			descTable.addCell(cell1);			
			cell1.setBorderWidth(0);
			
			Image image = null;
			if ((rating == null) || (rating.hasSkill() == false)) {
				log.debug("rating does not have skill, showing 'x'");
				image = Image.getInstance("http://localhost/hrs-intranet/graphics/x_sml.gif");
			}
			else {
				log.debug("rating has skill, showing check");
				image = Image.getInstance("http://localhost/hrs-intranet/graphics/check_sml.gif");
			}
			if (image == null) {
				log.error("image is null");
			}
			else {  
				image.scalePercent(75f);
				image.setAlignment(Image.MIDDLE);
				PdfPCell cellIcon = new PdfPCell(image);
				cellIcon.setPadding(3);
				cellIcon.setBorderWidth(0);
				descTable.addCell(cellIcon);
			}
			
			PdfPCell cell2 = new PdfPCell(ReportUtil.createPhrase(parentSkill.getDescription(), ReportConstants.smlFont));
			cell2.setBorderWidth(0);
			descTable.addCell(cell2); 
			
			
			PdfPCell cell = new PdfPCell(descTable);
			cell.setBackgroundColor(color);
			if (ratingDesc.length() <= 0)
				ratingDesc = " ";
			cell2 = new PdfPCell(ReportUtil.createPhrase(ratingDesc, ReportConstants.smlFont));
			cell2.setBackgroundColor(color);
			table.addCell(cell);	
			table.addCell(cell2);	
		}
		catch (Exception ex) {
			log.error("Exception caught while adding skill row = " + parentSkill.getSkillCode(), ex);
			throw new VectricsException("Exception caught while adding job row for job = " + parentSkill.getSkillCode(), ex);
		}	
	}   
	
	
	
	void displaySkillBranch(PdfPTable table, Skill parentSkill, SkillRatingSet ratingSet, int level) throws VectricsException {
		displaySkill(table, parentSkill, ratingSet, level);
		TreeSet children = new TreeSet(new SkillChildComparator());
		children.addAll(parentSkill.getChildren());
		Iterator iter =  children.iterator();
		if ((this.getShowAllBranches()) || (this.skillSetUtil.getUserHasParentSkill(parentSkill))) {
			while (iter.hasNext()) {
				Skill child = (Skill)iter.next();
				displaySkillBranch(table, child, ratingSet, level + 1);
			}
		}
	}
	
*/    
	protected void setupHeaderFooter(Document document) throws VectricsException {
	}


	protected void addTableHeaderCell(String title) {
		log.debug("addTableHeaderCell()");
		PdfPCell hdrCell = new PdfPCell(new Phrase(title, ReportConstants.stdBoldFont));
		hdrCell.setBackgroundColor(ReportConstants.TABLE_HEAD_COLOR);
		this.mainTable.addCell(hdrCell);	
	}
	   

	/**
	 * @return Returns the evaluationId.
	 */
	public String getEvaluationId() {
		return evaluationId;
	}

	/**
	 * @param evaluationId The evaluationId to set.
	 */
	public void setEvaluationId(String evaluationId) {
		this.evaluationId = evaluationId;
	}

	/**
	 * @return Returns the userId.
	 */
	public String getUserId() {
		return userId;
	}

	/**
	 * @param userId The userId to set.
	 */
	public void setUserId(String userId) {
		this.userId = userId;
	}

	
	
	
/*	

	void showSkills(Skill rootSkill, SkillRatingSet owner, Skill parent, Table table, int indent) {
		if (log.isDebugEnabled())
			log.debug("showSkills()  parent: " + parent.getSkillCode());
		Iterator iter = parent.getChildren().iterator();
		while (iter.hasNext()) {
			Skill childSkill = (Skill)iter.next();
			showSkill(rootSkill, owner, childSkill, table, indent);
			SkillSetUtil util = new SkillSetUtil(owner, rootSkill.getTree());
			if (util.getUserHasParentSkill(childSkill)) {
				showSkills(rootSkill, owner, childSkill, table, indent + 1);
			}
		}
		
	}
	
	void showSkill(Skill rootSkill, SkillRatingSet owner, Skill skill, Table table, int indent) {
		if (log.isDebugEnabled())
			log.debug("showSkill() called.  Skill = " + skill.getSkillCode());
		SkillRating rating = owner.findSkillRating(skill);
		log.debug("showSkill() - making row for skill");
		Row row2 = table.addRow();
		//Cell categoryCell = row2.addCell();
		Cell descCell = row2.addCell();
		Cell ratingCell = row2.addCell();

		Table descTable = new Table();
		descTable.setCellPadding(0);
		descTable.setCellSpacing(0);
		descTable.setBorder(0);
		Row descRow = descTable.addRow();
		

		log.debug("showSkill() - building indention for skill rating on hierarchy.");
		for (int i = 0; i < indent; i++) {
			Cell indentCell = descRow.addCell();
			indentCell.addElement(makeIndentImage());
		}
		
		IMG img = new IMG();
		img.setSrc("/recruit/graphics/check_sml.gif");
		img.setAlt("");
		img.setBorder(0);
		img.setHeight(12);
		img.setWidth(12);
		
		
		if (rating == null) {
			SkillSetUtil util = new SkillSetUtil(owner, rootSkill.getTree());
			if (util.getUserHasParentSkill(skill) == false) {
				img.setSrc("/recruit/graphics/x_sml.gif");
			}
		}
		
		descRow.addCell().addElement(img);


		log.debug("showSkill() - adding skill desc to cell.");
		//categoryCell.addElement(TextHelper.getFont("stdFont", indentStr); //categoryText));
		descRow.addCell().addElement(TextHelper.getFont("subFont", skill.getDescription()));
		descCell.addElement(descTable);
		
		log.debug("showSkill() - adding skill rating description to cell.");
		if (rating == null) {
			// ratingCell.addElement(TextHelper.getFont("stdFont", ""));
		}
		else {
			if (editMode == true) {
				if (getShowSkillDetails()) {
					if (skill.getNeedsLevel())
						ratingCell.addElement(SkillGui.makeSkillLevelTable(rating, skill));
					if (skill.getNeedsYears())
						SkillGui.displayYears(rating, skill, ratingCell);
					if (skill.getNeedsYesNo())
						SkillGui.displayYesNo(rating, skill, ratingCell);
				}
				else {
					ratingCell.addElement(SkillGui.makeSkillLevelTable(rating, skill));
				}
				
			}
			else {
				ratingCell.addElement(TextHelper.getFont("subFont", rating.getDescription()));
			}
		}
		log.debug("showSkill() - done.");
	}
	
	
	private IMG makeIndentImage() {
		
		IMG img = new IMG();
		img.setSrc("/recruit/graphics/cleardot.gif");
		img.setAlt("");
		img.setBorder(0);
		img.setHeight(10);
		img.setWidth(10);
		return(img);
	}
*/	
	
	public boolean getShowAllBranches() {
		return showAllBranches;
	}


	public void setShowAllBranches(boolean showAllBranches) {
		this.showAllBranches = showAllBranches;
	}

}
